// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

const db = cloud.database()
const _ = db.command
const $ = db.command.aggregate

/**
 * 查询用户提交的申请或线索
 */
exports.main = async (event, context) => {
  const { OPENID } = cloud.getWXContext()
  const res = await db.collection('request')
    .aggregate()
    .match({
      _openid: OPENID,
      type: event.type
    })
    .lookup({
      from: 'notice',
      localField: 'notice_id',
      foreignField: '_id',
      as: 'notices',
    })
    .replaceRoot({
      newRoot: $.mergeObjects([ $.arrayElemAt(['$notices', 0]), '$$ROOT' ])
    })
    .project({
      _openid: 1,
      notice_id: 1,
      receiver_id: 1,
      requester: 1,
      phone: 1,
      images: 1,
      region: 1,
      description: 1,
      status: 1,
      tosee: 1,
      create: 1,
      title: 1
    })
    .sort({
      tosee: -1,
      create: -1
    })
    .end()
  return res
}